import _ from 'underscore';
import Mn from "backbone.marionette";
import Radio from 'backbone.radio';
import ExpenseFileItemView from "./ExpenseFileItemView";

const template = require('./templates/ExpenseFileCollectionView.mustache');

const Emptyview = Mn.View.extend({
    tagName: 'tr',
    template: _.template(
        '<td colspan=10 class=col_text><em>Aucun justificatif non lié à une dépense.</em></td>'
    ),
});

const ExpenseFileCollectionView = Mn.CollectionView.extend({
    tagName: 'tbody',
    template: template,
    childView: ExpenseFileItemView,
    emptyView: Emptyview,
    childViewTriggers: {
        'file:delete': 'file:delete',
        'file:link_to_expenseline': 'file:link_to_expenseline',
        'file:new_expense': 'file:new_expense',
    },
    _onCollectionUpdate(){
        // Quite hackish : bypass CollectionView optimizations on fine-grained
        // child rendering : re-render the whole thing, allowing the files
        // counter displayed by template to update.
        this.render();
    },
    initialize() {
        this.facade = Radio.channel('facade');
        this.listenTo(
            this.facade,
            'linkedFilesChanged',
            function(){
                this.updateLinkedFiles();
                this.render();  // re-apply filters
            },
            this,
        );
        this.updateLinkedFiles(); // initialization
    },
    childViewOptions(){
        return {
            edit: this.getOption('edit'),
            is_achat: this.getOption('is_achat'),
            can_validate_attachments: this.getOption('can_validate_attachments'),
        };
    },
    viewFilter(view, index, children) {
        return ! this.linkedFileIds.has(view.model.id);
    },
    updateLinkedFiles(){
        this.linkedFileIds = this.facade.request('get:linkedFiles');
    },
    getItemsCount(){
        // I don't see any better way than filtering twice to count…
        return this.children.filter(x => this.viewFilter(x)).length;
    },
    templateContext(){
        let items_count = this.getItemsCount();
        return {
            items_count: items_count,
            pluralize: items_count > 1 ? 's' : '',
        };
    },

});
export default ExpenseFileCollectionView;
